﻿using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Web.Mvc;
using System.Web.Routing;
using AutoMapper;
using ContactCenter.Core.DomainModel;
using ContactCenter.UI.Web.Extensibility;
using ContactCenter.UI.Web.Models;
using StructureMap;

namespace ContactCenter.UI.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static IContainer _container;
        private static readonly object _padLock = new object();

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("favicon.ico");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            PrepareContainer();

            AreaRegistration.RegisterAllAreas();

            // Use LocalDB for Entity Framework by default
            Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            InitMapping();

            ControllerBuilder.Current.SetControllerFactory(new MyAppControllerFactory(_container));
        }

        private static void PrepareContainer()
        {
            if (_container != null) return;

            lock (_padLock)
            {
                ObjectFactory.Initialize(c => c.AddRegistry(new StartupRegistry()));

                _container = ObjectFactory.Container.RunBootstrapperJobs();
            }
        }

        private static void InitMapping()
        {
            Mapper.CreateMap(typeof(Address), typeof(AddressDTO));
            Mapper.CreateMap(typeof(ContactInfo), typeof(ContactInfoDTO)).ConvertUsing(typeof(ContactInfoTypeConverter));
            Mapper.CreateMap(typeof(CreditCard), typeof(CreditCardDTO));
            Mapper.CreateMap<CreditCardDTO, CreditCard>();
            Mapper.CreateMap<ContactInfoDTO, ContactInfo>();
            Mapper.CreateMap<Customer, CustomerDTO>();

            Mapper.AssertConfigurationIsValid();
        }

        public override void Init()
        {
            base.Init();
            _container.InitHttpModules(x => x.Init(this));
        }
    }
}